<?php

namespace app\home\controller;

use app\common\model\Goods;
use think\Request;

class Product extends Common
{
    
    public $user;
    
    public function initialize()
    {
        parent::initialize();
        if (!session('uid')) {
            header('location:' . url('/login'));
        }
    }
    
    public function index(Goods $goods)
    {
         $cid = $_GET['cid']??0;
         $cid = (int)$cid;
         $keywords = $_GET['keywords']??"";

        $map = [];
        $model = $goods
             ->where($map);
        $p_cid = 0;
        if($cid>0){
            $cid_ar = \db('goods_cat')->where('id', $cid)->find();
            if($cid_ar){
                $p_cid = $cid_ar['pid'];
                $p_cid = $p_cid>0?$p_cid:$cid;
                $model->where("cid",$cid);
            }
        }
        if($keywords){
            $model->where("title","like","%".$keywords."%");
            $model->whereOr("title_cn","like","%".$keywords."%");
        }

        $list = $model ->order('sort asc,create_time desc')->paginate($this->pagesize);

//        $sql = $model->getLastSql();
//        dump($sql);die;

        // 获取分页显示
        $page = $list->render();
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {

        }
        $this->assign('list', $list['data']);
        $this->assign('page', $page);
        $this->assign('cid', $cid);
        $this->assign('p_cid', $p_cid);
        return $this->fetch();
    }
    
    
    public function show(Goods $goods, $id = 0)
    {
        $info = $goods->find($id);
        if (empty($info)) {
            $this->error('商品不存在');
        }
        if (isset_full($info, 'imgs')) {
            $info['imgs'] = explode(';', $info['imgs']);
        }
        $list = $goods->limit(8)->order(rand())->select();
        $this->assign('info', $info);
        $this->assign('list', $list);
        return $this->fetch();
    }
    
}